package io.sundial.util;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 组合的枚举器
 *
 * @author Payne 646742615@qq.com
 * 2018/12/14 17:37
 */
public class MultipleEnumeration<E> implements Enumeration<E> {
    private final Iterator<? extends Enumeration<E>> iterator;
    private volatile Enumeration<E> current;

    public MultipleEnumeration(Enumeration<E> first, Enumeration<E> second) {
        this(Arrays.asList(first, second));
    }

    public MultipleEnumeration(Enumeration<E> first, Enumeration<E> second, Enumeration<E> third) {
        this(Arrays.asList(first, second, third));
    }

    public MultipleEnumeration(Iterable<? extends Enumeration<E>> iterable) {
        this.iterator = iterable.iterator();
    }

    @Override
    public boolean hasMoreElements() {
        if (current == null || !current.hasMoreElements()) {
            if (iterator.hasNext()) {
                current = iterator.next();
                return hasMoreElements();
            }
            return false;
        }
        return true;
    }

    @Override
    public E nextElement() {
        if (hasMoreElements()) {
            return current.nextElement();
        }
        throw new NoSuchElementException();
    }
}
